package com.example.shoppingmallspringboot.service.impl;

import com.example.shoppingmallspringboot.entity.User;
import com.example.shoppingmallspringboot.mapper.UserMapper;
import com.example.shoppingmallspringboot.service.UserProfileService;
import com.example.shoppingmallspringboot.util.FwResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Service
public class UserProfileServiceImpl implements UserProfileService {
    
    @Autowired
    private RedisTemplate redisTemplate;
    
    @Autowired
    private UserMapper userMapper;

    @Override
    public FwResult upload(MultipartFile file, String token) throws IOException {
        User user = (User) redisTemplate.opsForValue().get(token);
        Integer userId = user.getId();
        
        if (file.isEmpty()) {
            return FwResult.okMsg("文件不存在");
        }
        
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = "userprofile" + userId + suffix;
        String newProfile = "images/" + fileName;
        
        // 更新用户头像路径
        user.setProfile(newProfile);
        userMapper.updateById(user);
        
        // 更新 Redis 中的用户信息
        redisTemplate.opsForValue().set(token, user, 1440, TimeUnit.MINUTES);
        
        // 保存文件
        String savePath = System.getProperty("user.dir") + "/files/images/" + fileName;
        try {
            file.transferTo(new File(savePath));
        } catch (IOException e) {
            System.out.println("文件上传出错");
            throw e;
        }
        
        return FwResult.ok(fileName, "上传成功");
    }
} 